/********
通用脚本  2020-09-21 15:36
********/

//共用页面
$(function() {
        //头部
        $('.header').load('./common/header.html', function() {
            fun_islogin();

            getQueryString();
            var search_keyword = getQueryString('search');

            $(".header .input_search").val(search_keyword)
        });
        //footer
        $('.footer_wrap').load('./common/footer.html');

    })
    //判断登录
var page_token = false;
var page_user = false;
var page_id = false;
var page_roleCode = false;
var page_roleId = false;

if (window.localStorage) {
    if (localStorage.getItem("token")) {
        page_token = localStorage.getItem("token");
    }
    if (localStorage.getItem("userName")) {
        page_user = localStorage.getItem("userName");
    }
    if (localStorage.getItem("userId")) {
        page_id = localStorage.getItem("userId");
    }
    if (localStorage.getItem("roleCode")) {
        page_roleCode = localStorage.getItem("roleCode");
    }
    if (localStorage.getItem("id")) {
        page_roleId = localStorage.getItem("id");
    }
} else {
    if ($.cookie("token")) {
        page_token = $.cookie("token");
    }
    if ($.cookie("userName")) {
        page_user = $.cookie("userName");
    }
    if ($.cookie("userId")) {
        page_id = $.cookie("userId");
    }
    if ($.cookie("roleCode")) {
        page_roleCode = $.cookie("roleCode");
    }
    if ($.cookie("id")) {
        page_roleId = $.cookie("id");
    }
}
//改变头部
function fun_islogin(getout) {

    if (page_token && page_user) {

        $(".header .login").hide();

        $(".header .username").show().attr("href", page_baseurl + "/#/sso?userid=" + page_id + "&token=" + page_token + "&name=" + page_user + "&rolecode=" + page_roleCode + "&id=" + page_roleId); //跳往相应用户中心;

        $(".header .signout").show();

        $(".header .usercenter").attr("href", page_baseurl + "/#/sso?userid=" + page_id + "&token=" + page_token + "&name=" + page_user + "&rolecode=" + page_roleCode + "&id=" + page_roleId); //跳往相应用户中心
        $(".footer .usercenter").attr("href", page_baseurl + "/#/sso?userid=" + page_id + "&token=" + page_token + "&name=" + page_user + "&rolecode=" + page_roleCode + "&id=" + page_roleId); //跳往相应用户中心

        if (page_roleCode == "student") {
            $(".header .document_center").attr("href", "./document_center.html?type=0");
            $(".footer .document_center").attr("href", "./document_center.html?type=0");
        }
        if (page_roleCode == "teacher") {
            $(".header .document_center").attr("href", "./document_center.html?type=1");
            $(".footer .document_center").attr("href", "./document_center.html?type=1");
        }
        if (page_roleCode == "referee") {
            $(".header .document_center").attr("href", "./document_center.html?type=2");
            $(".footer .document_center").attr("href", "./document_center.html?type=2");
        }
        if (page_roleCode == "examin") {
            $(".header .document_center").attr("href", "./document_center.html?type=3");
            $(".footer .document_center").attr("href", "./document_center.html?type=3");
        }


        if (page_user) {
            $(".header .username").text(page_user);
            $(".m_header .username").text(page_user);
        } else {
            $(".header .username").text("已登录");
        }
    } else {
        $(".header .login").show();
        if (getout) {
            //location.replace("./login.html");
        }
    }
}

//退出登录
$(document).on("click", ".header .signout", function() {
    if (window.localStorage) {
        //localStorage.clear();
        localStorage.removeItem("token");
        localStorage.removeItem("userName");
        localStorage.removeItem("userId");
        localStorage.removeItem("roleCode");
    } else {
        $.cookie("token", null);
        $.cookie("userName", null);
        $.cookie("userId", null);
        $.cookie("roleCode", null);
    }
    window.location.replace("./index.html");
});

$(document).on("click", "#m_header .signout", function() {
    if (window.localStorage) {
        //localStorage.clear();
        localStorage.removeItem("token");
        localStorage.removeItem("userName");
        localStorage.removeItem("userId");
    } else {
        $.cookie("token", null);
        $.cookie("userName", null);
        $.cookie("userId", null);
    }
    window.location.replace("../index.html");
});



/** 浏览器环境
browser["b"] 浏览器
browser["v"] 版本
browser["m"] 是否移动端
browser["wx"] 是否在微信环境中
**/
browser = (function(ua) {
    var a = new Object();
    var b = {
        //micromessenger: /micromessenger/.test(ua),
        msie: /msie/.test(ua) && !/opera/.test(ua),
        opera: /opera/.test(ua),
        safari: /webkit/.test(ua) && !/chrome/.test(ua),
        firefox: /firefox/.test(ua),
        edge: /edge/.test(ua),
        trident: /trident/.test(ua),
        chrome: /chrome/.test(ua)
    };
    var vMark = "";
    for (var i in b) {
        if (b[i]) { vMark = i; break; } //"safari" == i ? "version" : i;
    }
    b.version = vMark && RegExp("(?:" + vMark + ")[\\/: ]([\\d.]+)").test(ua) ? RegExp.$1 : "0";
    b.ie = b.msie;
    b.ie6 = b.msie && parseInt(b.version, 10) == 6;
    b.ie7 = b.msie && parseInt(b.version, 10) == 7;
    b.ie8 = b.msie && parseInt(b.version, 10) == 8;

    //if(vMark == "trident") vMark = "ie11";

    a.b = vMark;
    a.v = b.version;
    a.m = /mobile/i.test(ua);
    a.wx = /MicroMessenger/i.test(ua);
    return a;
})(window.navigator.userAgent.toLowerCase());
/** 浏览器环境 结束 **/

//网站地址
if (!isValidityUrl(site_url)) {
    var site_url = "/";
}

/**
锁定body禁止滚屏
UPDATE: 2018/04/25
上次版本: 2018/04/02
**/
function bodyfixed(restore) {
    var tmp_fixed_num = $("body").data("fixed_num") ? $("body").data("fixed_num") : 0;
    if (restore == 0) {
        (tmp_fixed_num > 0) ? tmp_fixed_num-- : (tmp_fixed_num = 0);
        $("body").data("fixed_num", tmp_fixed_num);
        if (!tmp_fixed_num) {
            var tmp_scrollTop = $("body").data("scrollTop");
            $("body").removeClass("fixed")
                .css("margin-top", $("body").data("margin-top"))
                .removeData("margin-top scrollTop");
            $(document).scrollTop(tmp_scrollTop);
        }
    } else {
        if (!$("body").data("scrollTop")) {
            $("body").data({ "margin-top": $("body").css("margin-top"), "scrollTop": $(document).scrollTop() });
        }
        $("body").css("margin-top", ($("body").data("margin-top").replace("px", "") - $("body").data("scrollTop")))
            .addClass("fixed");
        $("body").data("fixed_num", (tmp_fixed_num + 1));
        $(".mask").on("touchmove", function(e) {
            e.preventDefault();
        });
    }
}

/**
快速闪现提示
UPDATE: 2018/09/06
上一版本: 2016/12/30
Powered by Joyton & dline.com.cn
用法：
$.fn.winktips({
  con: "内容",
  delay: 1600, //存活时间，默认1600
  pointer: false //是否可以点击
});
简单用法：
$.fn.winktips("内容");

**/
(function($) {
    $.fn.winktips = function(options) {
        var defaults = {
            con: "(•ᴗ•)و",
            delay: 1600,
            pointer: false
        };
        if ((typeof options != "object")) {
            defaults.con = options;
        }
        var settings = $.extend({}, defaults, options);

        if (!$("#winktips").length) {
            $("body").append("<div id=\"winktips\"></div>");
        }
        $("<div class=\"item" + (settings.pointer ? " pointer" : "") + "\"><span>" + settings.con + "</span></div>").appendTo("#winktips").fadeIn(200).delay(settings.delay).fadeOut(200, function() {
            $(this).remove();
        });
        return this;

    }
})(jQuery);
/** 快速闪现提示插件 结束 **/


/**
弹出提示
UPDATE: 2017/12/27
上次版本: 2017/12/04
Powered by Joyton & dline.com.cn
用法：
$.fn.poptips({
  title: "标题", //默认为空
  con: "内容",
  conCenter: false, //文本内容内容是否居中，默认居中
  btnOK: false, //是否显示确认按钮 默认显示
  btnCancel: false, //是否显示取消按钮 默认不显示
  btnOKText: "确认", //确认按钮的文案
  btnCancelText: "取消", //取消按钮的文案
  btnOKClick: function (){	//确认按钮点击事件（没有按钮时遵从此事件）
    console.log("你点了确认");
  },
  btnCancelClick: function (){	//取消按钮点击事件
    console.log("你点了取消");
  }
});
简单用法：
$.fn.poptips("内容");

**/
(function($) {
    $.fn.poptips = function(options) {
        var defaults = {
            title: "",
            con: "无内容",
            conCenter: true,
            btnOK: true,
            btnCancel: false,
            btnOKText: "确认",
            btnCancelText: "取消",
            "btnOKClick": function() {},
            "btnCancelClick": function() {}
        };

        if ((typeof options != "object")) {
            defaults.con = options;
        }

        var settings = $.extend({}, defaults, options);

        var tmp_html = "";
        tmp_html += "<div id=\"poptips\"><div class=\"poptips_box\">" +
            (settings.title ? "<div class=\"title\">" + settings.title + "</div>" : "") +
            "<div class=\"con " +
            (settings.conCenter ? "center" : "") +
            "\">" + settings.con +
            "</div>";
        if (settings.btnCancel || settings.btnOK) {
            tmp_html += "<div class=\"btn_group\">" +
                (settings.btnCancel ? "<a class=\"btn cancel\">" + settings.btnCancelText + "</a>" : "") +
                (settings.btnOK ? "<a class=\"btn ok\">" + settings.btnOKText + "</a>" : "") +
                "</div>";
        }
        tmp_html += "</div></div>";

        $("#poptips").remove();
        $("body").append(tmp_html);

        try {
            var scrollbarWidth = window.innerWidth - $(window).width();
            if (scrollbarWidth >= 20 || scrollbarWidth < 0) {
                scrollbarWidth = 0;
            }
        } catch (e) {
            var scrollbarWidth = 0;
        }

        $("body").addClass("poptips_show").css("padding-right", scrollbarWidth + "px");

        if ($("#poptips .con").height() > $(window).height() - 100) {
            $("#poptips .con").css("max-height", $(window).height() - 180 + "px");
        }

        $("#poptips .poptips_box").css("top", ($(window).height() - $("#poptips .poptips_box").height()) / 2 - 10 + "px");

        var poptips_scrolltop = 0;
        var tmp_poptips_scrolltop = 0;
        $("body").on({
            "touchstart.poptips": function(e) {
                var touch = e.touches[0];
                tmp_poptips_scrolltop = touch.pageY;
            },
            "touchmove.poptips": function(e) { //$(e.target)
                var touch = e.touches[0];
                var tmp_height_real = $("#poptips .con")[0].scrollHeight;
                if (touch.pageY - tmp_poptips_scrolltop > 0 && $("#poptips .con").scrollTop() <= 0) {
                    return false;
                }
                if (touch.pageY - tmp_poptips_scrolltop < 0 && $("#poptips .con").scrollTop() >= (tmp_height_real - $("#poptips .con").outerHeight())) {
                    return false;
                }
            },
            "touchend.poptips": function(e) {}
        });
        $(window).on({
            "resize.poptips": function(e) {
                try {
                    var scrollbarWidth = window.innerWidth - $(window).width();
                    if (scrollbarWidth >= 20 || scrollbarWidth < 0) {
                        scrollbarWidth = 0;
                    }
                } catch (e) {
                    var scrollbarWidth = 0;
                }

                $("body").addClass("poptips_show").css("padding-right", scrollbarWidth + "px");

                if ($("#poptips .con").height() > $(window).height() - 100) {
                    $("#poptips .con").css("max-height", $(window).height() - 180 + "px");
                }

                $("#poptips .poptips_box").css("top", ($(window).height() - $("#poptips .poptips_box").height()) / 2 - 10 + "px");
            }
        });

        function fun_closepoptips(e) {
            e.stopPropagation();
            $("body").removeClass("poptips_show").css("padding-right", "");
            $("body").off(".poptips", "#poptips .ok")
                .off(".poptips", "#poptips .cancel")
                .off(".poptips", "#poptips")
                .off("touchstart.poptips")
                .off("touchmove.poptips")
                .off("touchend.poptips");
            $(window).off("resize.poptips");
        }

        if (!settings.btnOK && !settings.btnCancel) {
            $("body").on("click.poptips", "#poptips", function(e) {
                fun_closepoptips(e);
                settings.btnOKClick();
            });
            $("#poptips").css("cursor", "pointer");
        } else {
            $("#poptips").css("cursor", "");
            $("body").on("click.poptips", "#poptips .ok", function(e) {
                fun_closepoptips(e);
                settings.btnOKClick();
            });
            $("body").on("click.poptips", "#poptips .cancel", function(e) {
                fun_closepoptips(e);
                settings.btnCancelClick();
            });
        }

    }
})(jQuery);
/** 弹出提示插件 结束 **/


/**图片按需懒加载
UPDATE: 2017/07/31
data-lazyimg="" 图片src
data-lazybgimg="" 背景图
**/
function lazy() {
    var lazyimg = 0;
    var lazybgimg = 0;

    var window_pageYOffset = window.pageYOffset || document.documentElement.scrollTop;
    var window_innerHeight = window.innerHeight || document.documentElement.offsetHeight;

    $("img[data-lazyimg]").each(function(index, val) {
        var valTop = $(val).offset().top;
        var valHeight = valTop + $(val)[0].offsetHeight; //$(val).height()

        if ((valTop >= window_pageYOffset &&
                valTop <= (window_pageYOffset + window_innerHeight)) || (valHeight >= window_pageYOffset && valHeight <= (window_pageYOffset + window_innerHeight))) {

            //载入图片
            var img = new Image();
            img.src = $(val).attr("data-lazyimg");
            $(val).removeAttr("data-lazyimg");
            $(val).attr("data-lazyimgloading", img.src);
            img.onload = function() {
                $(val).attr("src", img.src);
                $(val).removeAttr("data-lazyimgloading");
            };

        }
        lazyimg++;
    });
    //console.log( lazyimg );


    $("[data-lazybgimg]").each(function(index, val) {
        var valTop = $(val).offset().top;
        var valHeight = valTop + $(val)[0].offsetHeight; //$(val).height()

        if ((valTop >= window_pageYOffset &&
                valTop <= (window_pageYOffset + window_innerHeight)) || (valHeight >= window_pageYOffset && valHeight <= (window_pageYOffset + window_innerHeight))) {
            //$(val).css("backgroundImage", "url(" + $(val).attr("data-lazybgimg") + ")");
            //$(val).removeAttr("data-lazybgimg");

            //载入图片
            var img = new Image();
            img.src = $(val).attr("data-lazybgimg");
            $(val).removeAttr("data-lazybgimg");
            $(val).attr("data-lazybgimgloading", img.src);
            img.onload = function() {
                $(val).css("backgroundImage", "url(" + img.src + ")");
                $(val).removeAttr("data-lazybgimgloading");
            };

        }
        lazybgimg++;

    });
}
$(function() {
    lazy();
});
$(window).on("scroll resize orientationchange", function() {
    lazy();
});
/** 图片按需懒加载 结束 **/


/**
菜单排序，将当前项置顶
UPDATE: 2016/09/20
用法：
$("#xxx").menuSort();
为置顶项添加class notsort
**/
(function($) {
    $.fn.menuSort = function() {
        return this.each(function() {
            if (!$(this).find(".active").hasClass("notsort")) {
                if ($(this).find(".notsort").length) {
                    var tmp_notsort = $(this).find(".notsort:last");
                    $(this).find(".active").insertAfter(tmp_notsort);
                } else {
                    $(this).find(".active").prependTo(this);
                }
            }
        });
    }
})(jQuery);
/** 菜单排序，将当前项置顶 结束 **/

/**
筛选区 单选开关
UPDATE: 2016/09/20
用法：
$(".tab_filter_item_toggle").tabFilterToggle(function (){});
**/
(function($) {
    $.fn.tabFilterToggle = function(afterFn) {
        if ((typeof afterFn != "function")) {
            afterFn = function() {};
        }
        return this.on("click", function() {
            $(this).toggleClass("active");
            if ($(this).hasClass("active")) {
                $(this).find("input").val($(this).find(".on").attr("rel"));
            } else {
                $(this).find("input").val($(this).find(".off").attr("rel"));
            }
            afterFn();
        });
    }
})(jQuery);
/** 筛选区 单选开关 结束 **/

/**
筛选区 菜单
UPDATE: 2016/10/24
用法：
$(".tab_filter_item .dropdown_menu").tabFilterMenu(function (){});
**/
(function($) {
    $.fn.tabFilterMenu = function(afterFn) {
        if ((typeof afterFn != "function")) {
            afterFn = function() {};
        }
        return this.on("click", ".menu_item", function() {
            var tmp_is_change = 1;
            var $tmp_tab_filter_item = $(this).parents(".tab_filter_item");
            $tmp_tab_filter_item.find("input").val($(this).attr("rel"));
            $tmp_tab_filter_item.find(".dropdown").text($(this).text());
            if ($(this).hasClass("active")) tmp_is_change = 0;
            $(this).addClass("active").siblings(".menu_item").removeClass("active");
            $tmp_tab_filter_item.find(".dropdown_menu").hide();
            $("body").off("click");
            afterFn(tmp_is_change);
        });
    }
})(jQuery);
/** 筛选区 菜单 结束 **/



/**
下拉滑动
UPDATE: 2016/10/13
简单用法：
$("#xxx").pullsurprise();
用法：
$("#xxx").pullsurprise({
  offset: 0, //拖动多少
  ing: function(tmp_t_y){}, //拖动中
  end: function(){} //拖动结束
});
**/
(function($) {
    $.fn.pullsurprise = function(options) {
        var defaults = {
            offset: 0,
            limit: 0,
            ing: function() {},
            end: function() {}
        };
        var settings = $.extend({}, defaults, options);

        if (this[0]) {
            var $target = this;
        } else {
            var $target = $("body");
        }
        var pullsurprise = {};

        if (settings.limit != 0 && settings.limit <= settings.offset) {
            settings.limit = settings.offset + 1;
        }

        $target.on({
            "touchstart.pullsurprise": function(e) {
                var touch = e.touches[0];
                pullsurprise.t_x = touch.pageX;
                pullsurprise.t_y = touch.pageY;
                $target.css("transition", "");
            },
            "touchmove.pullsurprise": function(e) {
                var touch = e.touches[0];
                pullsurprise.tmp_t_x = touch.pageX - pullsurprise.t_x;
                pullsurprise.tmp_t_y = touch.pageY - pullsurprise.t_y;
                if (pullsurprise.tmp_t_y > 0) {
                    if ($(document).scrollTop() == 0) {
                        if (pullsurprise.tmp_t_y > pullsurprise.tmp_t_x) {
                            pullsurprise.tmp_ontop = 1;
                        }
                    }
                }
                if (pullsurprise.tmp_ontop == 1) {
                    $(document).on("touchmove.pullsurprise_tmp", function(e) {
                        e.preventDefault();
                    });
                    settings.ing(((pullsurprise.tmp_t_y > 0) ? pullsurprise.tmp_t_y : 0));
                    if (settings.limit != 0 && pullsurprise.tmp_t_y > settings.limit) {
                        pullsurprise.tmp_t_y = settings.limit;
                    }
                    $target.css({ "transform": "translate3d(0," + ((pullsurprise.tmp_t_y > 0) ? pullsurprise.tmp_t_y : 0) + "px,0)", "transition": "all 0s" });
                }
            },
            "touchend.pullsurprise": function(e) {
                if (pullsurprise.tmp_ontop == 1) {
                    if (pullsurprise.tmp_t_y > settings.offset) {
                        settings.end();
                    }
                    pullsurprise.tmp_t_y = 0;
                    pullsurprise.tmp_ontop = 0;
                    $target.css({ "transform": "", "transition": "all .3s" });
                    $(document).off("touchmove.pullsurprise_tmp");
                }
            }
        });
        return this;
    }
})(jQuery);




/**
表单提示
UPDATE: 2016/09/29
**/
(function($) {
    $.fn.checktips = function(options) {
        var defaults = {
            target: "", //焦点
            parent: "", //添加 haserror 的元素
            tips: "", //form_help 中的文字
            winktips: "", //快速闪现的提示文字
            act: "" //hide 为隐藏
        };
        var settings = $.extend({}, defaults, options);

        if (settings.act == "hide") {
            settings.parent.removeClass("haserror").find(".form_help").hide();
            return false;
        }

        if (settings.target) {
            settings.target.focus();
        }
        //this.focus();

        if (settings.tips) {
            settings.parent.addClass("haserror");
            if (!settings.parent.find(".form_help").length) {
                settings.parent.append("<div class=\"form_help\">" + settings.tips + "</div>");
            } else {
                settings.parent.find(".form_help").html(settings.tips).show();
            }
        }

        if (settings.winktips) {
            $.fn.winktips(settings.winktips);
        }

    }
})(jQuery);

//移除特殊字符
function stripscript(s) {
    var pattern = new RegExp("[%--`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]") //格式 RegExp("[在中间定义特殊过滤字符]")
    var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs;
}

//获取URL参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    //if (r != null) return unescape(r[2]); return null;
    if (r != null) return decodeURI(r[2]);
    return null;
}

//汉字转编码
function toUtf8(str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for (i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
        } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
}

/**
 * 用于把用utf16编码的字符转换成实体字符，以供后台存储
 * @param  {string} str 将要转换的字符串，其中含有utf16字符将被自动检出
 * @return {string}     转换后的字符串，utf16字符将被转换成&#xxxx;形式的实体字符
 */
function utf16toEntities(str) {
    var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
    str = str.replace(patt, function(char) {
        var H, L, code;
        if (char.length === 2) {
            H = char.charCodeAt(0); // 取出高位
            L = char.charCodeAt(1); // 取出低位
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
            return "&#" + code + ";";
        } else {
            return char;
        }
    });
    return str;
}

//验证URL有效性
function isValidityUrl(str) {
    var RegUrl = new RegExp();
    RegUrl.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+[A-Za-z0-9-_%&\?\/.=#]+?$");
    if (!RegUrl.test(str)) {
        return false;
    }
    return true;
}

//验证身份证号码有效性
function isValidityIdCard(idCard) {

    if (idCard.length < 18) {
        return false;
    }
    var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]; // 加权因子
    var ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; // 身份证验证位值.10代表X
    var sum = 0; // 声明加权求和变量
    if (idCard[17].toLowerCase() == 'x') {
        var tmp_vcode = 10; // 将最后位为x的验证码替换为10方便后续操作
    } else {
        var tmp_vcode = idCard[17];
    }

    for (var i = 0; i < 17; i++) {
        sum += Wi[i] * idCard[i]; // 加权求和
    }
    valCodePosition = sum % 11; // 得到验证码所位置   
    if (tmp_vcode == ValideCode[valCodePosition]) {
        return true;
    } else {
        return false;
    }
}

//通过身份证号获取生日性别等信息
function infoByIdCard(idCard) {
    var info = [];
    info["year"] = Math.floor(idCard.substring(6, 10));
    info["month"] = Math.floor(idCard.substring(10, 12));
    info["day"] = Math.floor(idCard.substring(12, 14));
    info["sex"] = (idCard.substring(14, 17) % 2 == 0) ? 1 : 2;
    return info;
}



/********************
促销倒计时 2018-02-28 09:25
上次版本 2018-01-16 13:25
options.callback($target_div, state);//0未开始 1进行中 2结束
********************/
(function($) {
    $.fn.promotioncountdown = function(options) {
        var defaults = {
            timestamp_offset: 0,
            text_notstarted: "据开始 【天】天 【时】:【分】:【秒】", //未开始完整文字
            text_notstarted_s1: "据开始 【天】天",
            text_notstarted_s2: "据开始 【时】:【分】:【秒】",
            text_ongoing: "据结束 【天】天 【时】:【分】:【秒】", //进行中完整文字
            text_ongoing_s1: "据结束 【天】天",
            text_ongoing_s2: "据结束 【时】:【分】:【秒】",
            text_end: "已结束",
            starttime: 0,
            endtime: 0,
            interval: 1000, //刷新间隔
            callback: function() {} //刷新后执行
        };

        var settings = $.extend({}, defaults, options);
        if ((typeof settings.callback != "function")) {
            settings.callback = function() {};
        }

        var $div_promotioncountdown = this;

        var interval_promotioncountdown;
        var tmp_html = "";

        function fun_text(tmp_html, lefttime) {
            tmp_html = tmp_html.replace("【天】", Math.floor(lefttime / 1000 / 60 / 60 / 24));
            tmp_html = tmp_html.replace("【时】", ("0" + Math.floor(lefttime / 1000 / 60 / 60 % 24)).slice(-2));
            tmp_html = tmp_html.replace("【分】", ("0" + Math.floor(lefttime / 1000 / 60 % 60)).slice(-2));
            tmp_html = tmp_html.replace("【秒】", ("0" + Math.floor(lefttime / 1000 % 60)).slice(-2));
            return tmp_html;
        }

        function fun_promotioncountdown(settings) {

            var now_timestamp = (new Date).getTime() + settings.timestamp_offset;
            clearInterval($div_promotioncountdown.data("interval_promotioncountdown"));
            clearInterval(interval_promotioncountdown);
            if (settings.starttime - now_timestamp > 0) { //未开始

                //console.log("未开始" + (settings.starttime - now_timestamp));

                interval_promotioncountdown = setInterval(function() {
                    var lefttime = settings.starttime - ((new Date).getTime() + settings.timestamp_offset);
                    if (lefttime / 1000 / 60 / 60 / 24 >= 1) {
                        if (settings.text_notstarted_s1) {
                            tmp_html = fun_text(settings.text_notstarted_s1, lefttime);
                        } else {
                            tmp_html = fun_text(settings.text_notstarted, lefttime);
                        }
                        $div_promotioncountdown.html(tmp_html);
                        settings.callback($div_promotioncountdown, 0);
                    } else if (lefttime > 0) {
                        if (settings.text_notstarted_s2) {
                            tmp_html = fun_text(settings.text_notstarted_s2, lefttime);
                        } else {
                            tmp_html = fun_text(settings.text_notstarted, lefttime);
                        }
                        $div_promotioncountdown.html(tmp_html);
                        settings.callback($div_promotioncountdown, 0);
                    } else { //结束
                        clearInterval(interval_promotioncountdown);
                        fun_promotioncountdown(settings);
                        $div_promotioncountdown.html(tmp_html);
                        settings.callback($div_promotioncountdown, 1);
                    }
                }, settings.interval);
                $div_promotioncountdown.data("interval_promotioncountdown", interval_promotioncountdown);
            } else {
                if (settings.endtime - now_timestamp > 0) { //进行中

                    //console.log("进行中" + (settings.endtime - now_timestamp));

                    interval_promotioncountdown = setInterval(function() {
                        var lefttime = settings.endtime - ((new Date).getTime() + settings.timestamp_offset);
                        if (lefttime / 1000 / 60 / 60 / 24 >= 1) {
                            if (settings.text_ongoing_s1) {
                                tmp_html = fun_text(settings.text_ongoing_s1, lefttime);
                            } else {
                                tmp_html = fun_text(settings.text_ongoing, lefttime);
                            }
                            $div_promotioncountdown.html(tmp_html);
                            settings.callback($div_promotioncountdown, 1);
                        } else if (lefttime > 0) {
                            if (settings.text_ongoing_s2) {
                                tmp_html = fun_text(settings.text_ongoing_s2, lefttime);
                            } else {
                                tmp_html = fun_text(settings.text_ongoing, lefttime);
                            }
                            $div_promotioncountdown.html(tmp_html);
                            settings.callback($div_promotioncountdown, 1);
                        } else { //结束
                            clearInterval(interval_promotioncountdown);
                            fun_promotioncountdown(settings);
                            $div_promotioncountdown.html(tmp_html);
                            settings.callback($div_promotioncountdown, 2);
                        }
                    }, settings.interval);
                    $div_promotioncountdown.data("interval_promotioncountdown", interval_promotioncountdown);
                } else { //已结束

                    //console.log("已结束");

                    tmp_html = settings.text_end;
                    $div_promotioncountdown.html(tmp_html);
                    settings.callback($div_promotioncountdown, 2);
                }
            }
        }

        fun_promotioncountdown(settings);

        return this;

    }
})(jQuery);




//获取用户定位信息 开始
//用法：get_userpoint( callback );
/********************
http://www.oschina.net/code/snippet_260395_39205

//WGS-84 to GCJ-02
GPS.gcj_encrypt(纬,经);

//GCJ-02 to BD-09
GPS.bd_encrypt(纬,经);

//求距离
GPS.distance(a纬,a经,b纬,b经);

********************/
var GPS = {
    PI: 3.14159265358979324,
    x_pi: 3.14159265358979324 * 3000.0 / 180.0,
    delta: function(lat, lon) {
        // Krasovsky 1940
        //
        // a = 6378245.0, 1/f = 298.3
        // b = a * (1 - f)
        // ee = (a^2 - b^2) / a^2;
        var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
        var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
        var dLat = this.transformLat(lon - 105.0, lat - 35.0);
        var dLon = this.transformLon(lon - 105.0, lat - 35.0);
        var radLat = lat / 180.0 * this.PI;
        var magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        var sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
        return { 'lat': dLat, 'lon': dLon };
    },

    //WGS-84 to GCJ-02
    gcj_encrypt: function(wgsLat, wgsLon) {
        if (this.outOfChina(wgsLat, wgsLon))
            return { 'lat': wgsLat, 'lon': wgsLon };

        var d = this.delta(wgsLat, wgsLon);
        return { 'lat': wgsLat + d.lat, 'lon': wgsLon + d.lon };
    },
    //GCJ-02 to WGS-84
    gcj_decrypt: function(gcjLat, gcjLon) {
        if (this.outOfChina(gcjLat, gcjLon))
            return { 'lat': gcjLat, 'lon': gcjLon };

        var d = this.delta(gcjLat, gcjLon);
        return { 'lat': gcjLat - d.lat, 'lon': gcjLon - d.lon };
    },
    //GCJ-02 to WGS-84 exactly
    gcj_decrypt_exact: function(gcjLat, gcjLon) {
        var initDelta = 0.01;
        var threshold = 0.000000001;
        var dLat = initDelta,
            dLon = initDelta;
        var mLat = gcjLat - dLat,
            mLon = gcjLon - dLon;
        var pLat = gcjLat + dLat,
            pLon = gcjLon + dLon;
        var wgsLat, wgsLon, i = 0;
        while (1) {
            wgsLat = (mLat + pLat) / 2;
            wgsLon = (mLon + pLon) / 2;
            var tmp = this.gcj_encrypt(wgsLat, wgsLon)
            dLat = tmp.lat - gcjLat;
            dLon = tmp.lon - gcjLon;
            if ((Math.abs(dLat) < threshold) && (Math.abs(dLon) < threshold))
                break;

            if (dLat > 0) pLat = wgsLat;
            else mLat = wgsLat;
            if (dLon > 0) pLon = wgsLon;
            else mLon = wgsLon;

            if (++i > 10000) break;
        }
        //console.log(i);
        return { 'lat': wgsLat, 'lon': wgsLon };
    },
    //GCJ-02 to BD-09
    bd_encrypt: function(gcjLat, gcjLon) {
        var x = gcjLon,
            y = gcjLat;
        var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * this.x_pi);
        var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * this.x_pi);
        bdLon = z * Math.cos(theta) + 0.0065;
        bdLat = z * Math.sin(theta) + 0.006;
        return { 'lat': bdLat, 'lon': bdLon };
    },
    //BD-09 to GCJ-02
    bd_decrypt: function(bdLat, bdLon) {
        var x = bdLon - 0.0065,
            y = bdLat - 0.006;
        var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * this.x_pi);
        var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * this.x_pi);
        var gcjLon = z * Math.cos(theta);
        var gcjLat = z * Math.sin(theta);
        return { 'lat': gcjLat, 'lon': gcjLon };
    },
    //WGS-84 to Web mercator
    //mercatorLat -> y mercatorLon -> x
    mercator_encrypt: function(wgsLat, wgsLon) {
        var x = wgsLon * 20037508.34 / 180.;
        var y = Math.log(Math.tan((90. + wgsLat) * this.PI / 360.)) / (this.PI / 180.);
        y = y * 20037508.34 / 180.;
        return { 'lat': y, 'lon': x };
        /*
        if ((Math.abs(wgsLon) > 180 || Math.abs(wgsLat) > 90))
            return null;
        var x = 6378137.0 * wgsLon * 0.017453292519943295;
        var a = wgsLat * 0.017453292519943295;
        var y = 3189068.5 * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)));
        return {'lat' : y, 'lon' : x};
        //*/
    },
    // Web mercator to WGS-84
    // mercatorLat -> y mercatorLon -> x
    mercator_decrypt: function(mercatorLat, mercatorLon) {
        var x = mercatorLon / 20037508.34 * 180.;
        var y = mercatorLat / 20037508.34 * 180.;
        y = 180 / this.PI * (2 * Math.atan(Math.exp(y * this.PI / 180.)) - this.PI / 2);
        return { 'lat': y, 'lon': x };
        /*
        if (Math.abs(mercatorLon) < 180 && Math.abs(mercatorLat) < 90)
            return null;
        if ((Math.abs(mercatorLon) > 20037508.3427892) || (Math.abs(mercatorLat) > 20037508.3427892))
            return null;
        var a = mercatorLon / 6378137.0 * 57.295779513082323;
        var x = a - (Math.floor(((a + 180.0) / 360.0)) * 360.0);
        var y = (1.5707963267948966 - (2.0 * Math.atan(Math.exp((-1.0 * mercatorLat) / 6378137.0)))) * 57.295779513082323;
        return {'lat' : y, 'lon' : x};
        //*/
    },
    // two point's distance
    distance: function(latA, lonA, latB, lonB) {
        var earthR = 6371000.;
        var x = Math.cos(latA * this.PI / 180.) * Math.cos(latB * this.PI / 180.) * Math.cos((lonA - lonB) * this.PI / 180);
        var y = Math.sin(latA * this.PI / 180.) * Math.sin(latB * this.PI / 180.);
        var s = x + y;
        if (s > 1) s = 1;
        if (s < -1) s = -1;
        var alpha = Math.acos(s);
        var distance = alpha * earthR;
        return distance;
    },
    outOfChina: function(lat, lon) {
        if (lon < 72.004 || lon > 137.8347)
            return true;
        if (lat < 0.8293 || lat > 55.8271)
            return true;
        return false;
    },
    transformLat: function(x, y) {
        var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
        return ret;
    },
    transformLon: function(x, y) {
        var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
        return ret;
    }
};


function baidumap_init_callback() {
    //根据浏览器定位
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {

            $("[name=userpoint_lng]").val(r.point.lng);
            $("[name=userpoint_lat]").val(r.point.lat);
            $("[name=userpoint_province]").val(r.address.province || "黑龙江省");
            $("[name=userpoint_city]").val(r.address.city || "");
            $("[name=userpoint_district]").val(r.address.district || "");
            if (window.localStorage) {
                localStorage.setItem("userpoint", JSON.stringify({
                    "timestamp": (new Date().getTime()),
                    "lng": $("[name=userpoint_lng]").val(),
                    "lat": $("[name=userpoint_lat]").val(),
                    "province": $("[name=userpoint_province]").val(),
                    "city": $("[name=userpoint_city]").val(),
                    "district": $("[name=userpoint_district]").val()
                }));
            }
        } else {
            $("[name=userpoint_lng]").val(116.33);
            $("[name=userpoint_lat]").val(39.89);
            $("[name=userpoint_province]").val("北京");
            $("[name=userpoint_city]").val("北京");
        }
    }, { enableHighAccuracy: true });
}
//异步加载百度地图js
function baidumap_script(next) {
    if (typeof(BMap) != "undefined") {
        baidumap_init_callback();
    } else {
        if (typeof(next) != "string") {
            next = "baidumap_init_callback";
        }
        var script = document.createElement("script");
        script.src = "https://api.map.baidu.com/api?v=2.0&ak=6n5d8gKH4ycOwtb92lkqdANbpP41t81S&callback=" + next; //<-注意 callback回调，同步加载没有&callback
        document.body.appendChild(script);
    }
}

function get_userpoint(callback) {

    if (!$("body [name=userpoint_lng]").length) {
        $("body").append("<input type=\"hidden\" name=\"userpoint_lng\"><input type=\"hidden\" name=\"userpoint_lat\">");
    }
    if (!$("body [name=userpoint_city]").length) {
        $("body").append("<input type=\"hidden\" name=\"userpoint_province\"><input type=\"hidden\" name=\"userpoint_city\"><input type=\"hidden\" name=\"userpoint_district\">");
    }

    //将坐标本地存储，30秒内无须请求新坐标
    if (window.localStorage) {
        var tmp_session_userpoint = localStorage.getItem("userpoint");
        if (tmp_session_userpoint) {
            if (typeof tmp_session_userpoint != "object") {
                tmp_session_userpoint = $.parseJSON(tmp_session_userpoint);
            }
            if (tmp_session_userpoint.hasOwnProperty("timestamp")) {
                if ((parseInt(tmp_session_userpoint.timestamp) + 1800000) > (new Date().getTime())) { //30000
                    $("[name=userpoint_lng]").val(tmp_session_userpoint.lng);
                    $("[name=userpoint_lat]").val(tmp_session_userpoint.lat);
                    $("[name=userpoint_province]").val(tmp_session_userpoint.province);
                    $("[name=userpoint_city]").val(tmp_session_userpoint.city);
                    $("[name=userpoint_district]").val(tmp_session_userpoint.district);
                }
            }
        }
    }

    if (!$("[name=userpoint_lng]").val()) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(updateLocation, baidumap_script);
        } else {
            //不支持定位
            baidumap_script();
        }
    }

    //
    function updateLocation(position) {
        if (position.coords.longitude || position.coords.latitude) {
            $("[name=userpoint_lng]").val(parseFloat(position.coords.longitude));
            $("[name=userpoint_lat]").val(parseFloat(position.coords.latitude));
            if (window.localStorage) {
                localStorage.setItem("userpoint", JSON.stringify({
                    "timestamp": (new Date().getTime()),
                    "lng": $("[name=userpoint_lng]").val(),
                    "lat": $("[name=userpoint_lat]").val()
                }));
            }
        }
    }

    //当获取到坐标后在进行进一步操作
    fn_userpoint_init();
    var tmp_trymore = setInterval(fn_userpoint_init, 1);

    function fn_userpoint_init() {
        if ($("[name=userpoint_lng]").val()) {
            clearInterval(tmp_trymore);
            callback();
        }
    }

}

//获取用户定位信息 结束


//通用下拉菜单
$(function() {
    $("html").on("click", ".dropdown", function(e) {
        var tmp_this = this;
        var $tmp_this_menu = $(this).next(".dropdown_menu").eq(0);
        //$(this).next( ".dropdown_menu" ).toggle();
        if ($tmp_this_menu.is(":visible")) {
            $tmp_this_menu.hide();

        } else {
            //$.fn.hasShadow();
            $tmp_this_menu.show();
            $("body").on("click.dropdown", function(e) {
                //if( $tmp_this_menu.is( ":visible" ) ) {
                var e = e || window.event;
                e.preventDefault && e.preventDefault();
                $tmp_this_menu.hide();
                $("body").off(".dropdown");
                return false;
                //}
            });
            var e = e || window.event;
            e.stopPropagation && e.stopPropagation();

            $tmp_this_menu.on("click", function(e) { //touchmove
                var e = e || window.event;
                e.stopPropagation && e.stopPropagation();
            });
        }
    });
});



//生成通用全屏黑幕（黑色遮罩）
(function($) {
    $.fn.hasShadow = function(options) {
        if (options == "hide") {
            $("#shadow").fadeOut("fast");
            $("body").off(".hasShadow")
                .removeClass("shadow_show")
                .css("margin-top", $("body").data("margin-top"))
                .removeData("margin-top scrollTop");
            $(document).scrollTop($("body").data("scrollTop"));
        } else {
            if (!$("#shadow").length) {
                $("body").append("<div id=\"shadow\"></div>");
            }
            $("#shadow").fadeIn("fast");
            $("body").on("touchmove.hasShadow", "#shadow", function(e) { //click
                return false;
            });
            if (!$("body").data("scrollTop")) {
                $("body").data({ "margin-top": $("body").css("margin-top"), "scrollTop": $(document).scrollTop() });
            }
            $("body").css("margin-top", ($("body").data("margin-top").replace("px", "") - $("body").data("scrollTop")))
                .addClass("shadow_show");
        }
    }
})(jQuery);


//通用页签切换
$(function() {
    $(".tab_nav_switch").on("click", "a", function() {
        //console.log( location.hash );
        if ($(this).data("for") != "") {
            $(this).siblings(".active").data("scrolltop", $(window).scrollTop()).removeClass("active");
            $(this).addClass("active");
            $($(this).data("for")).addClass("active").siblings(".tab_plate").removeClass("active");
            /*if( $(this).data("scrolltop") ) {
              $("html, body").animate( {scrollTop: $(this).data("scrolltop")}, "slow" );
            }*/
        }
        return false;
    });
});



/*
//通用展开
$(function(){
  $( ".card_more" ).on("click", function(){
    $(this).parents(".folded").each(function(){
      $(this).removeClass("folded");
      return false;
    });
  });
});

*/

//滚动屏幕自动载入新内容
//例：scrollLoad( $("#event_list_main .main_more"), -100 );
function scrollLoad(target, offset) {
    offset = offset || 0;
    if (target.length) {
        if ($(window).scrollTop() >= target.offset().top - $(window).height() - offset) {
            target.click();
        }
    }
}


/**
上传并裁切图片
UPDATE: 2017/11/27
上次版本: 2017/11/13
先这样，有空再改
用法：
$(".form_imgupload").cropimgupload(function (){});
**/
(function($) {
    $.fn.cropimgupload = function(options) {
        var defaults = {
            file_data: "",
            max_side: 640,
            max_height: 1000,
            aspect_ratio: 0,
            btnOKClick: function(data, btn) {},
            btnCancelClick: function(btn) {}
        };
        var settings = $.extend({}, defaults, options);

        //弹出界面
        if (!this[0]) {
            cropimgupload_init();
        } else {
            this.on("click", function() {
                cropimgupload_init();
            });
        }
        var $this_btn = this; //触发的按钮
        var jcrop_api;

        function cropimgupload_init() {


            var imgupload_x, imgupload_y, imgupload_w, imgupload_h;
            var imgupload_scale = 1;

            if ($(settings.file_data).val()) {
                $("#imgupload_preview").prop("src", $(settings.file_data).val());
                $("#imgupload_file_data").val($(settings.file_data).val());
            } else {
                $("#imgupload_preview").prop("src", $("#imgupload_preview").data("blank"));
                $("#submit_imgupload").hide();
            }

            //$.fn.hasShadow();
            //$("#part_imgupload").show();
            bodyfixed();
            $("#part_imgupload").removeClass("hide");

            try {
                jcrop_api.destroy();
            } catch (e) {}


            //获得图片原始尺寸
            function getImgNaturalDimensions(img, callback) {
                var nWidth, nHeight;
                if (img.naturalWidth) { // 现代浏览器
                    nWidth = img.naturalWidth;
                    nHeight = img.naturalHeight;
                } else { // IE6/7/8
                    var image = new Image()
                    image.src = img.src;
                    image.onload = function() {
                        callback(image.width, image.height);
                    }
                }
                return [nWidth, nHeight];
            }




            function updateCoords(c) {

                $("#btn_crop_ok").off(".click_crop_ok");
                $("#btn_crop_cancel").off(".click_crop_cancel");
                //确认裁切
                $("#btn_crop_ok").on("click.click_crop_ok", function() {

                    imgupload_scale = getImgNaturalDimensions(document.getElementById("imgupload_preview"))[0] / $("#imgupload_preview").width();

                    imgupload_x = c.x * imgupload_scale;
                    imgupload_y = c.y * imgupload_scale;
                    imgupload_w = c.w * imgupload_scale;
                    imgupload_h = c.h * imgupload_scale;

                    $.fn.getimgdata({
                        img: $("#imgupload_file_data").val(),
                        dir: 0,
                        crop_x: imgupload_x,
                        crop_y: imgupload_y,
                        crop_w: imgupload_w,
                        crop_h: imgupload_h,
                        next: function(data) {

                            $("#imgupload_preview").prop("src", data).css({ "width": "", "height": "" });

                            $("#imgupload_file_data").val(data);

                            try {
                                jcrop_api.destroy();
                            } catch (e) {}

                            $("#imgupload_preview").Jcrop({
                                aspectRatio: settings.aspect_ratio,
                                onSelect: updateCoords,
                                onRelease: function() {
                                    $("#btn_crop_ok").off(".click_crop_ok");
                                }
                            }, function() {
                                jcrop_api = this;
                            });

                            //imgupload_natural_w = getImgNaturalDimensions( document.getElementById("imgupload_preview") )[0];

                            //imgupload_natural_h = getImgNaturalDimensions( document.getElementById("imgupload_preview") )[1];

                        }
                    });

                    //$(this).hide();
                    $("#crop_bottombar").hide();
                    //$("#btn_crop_ok").off( ".click_crop_ok");
                });
                $("#btn_crop_cancel").on("click.click_crop_cancel", function() {
                    try {
                        jcrop_api.release();
                    } catch (e) {}
                    $("#crop_bottombar").hide();
                });

                $("#crop_bottombar").show();
                //$("#imgupload_bottombar").hide();
            };




            $("#imgupload_file").on("change.change_imgupload_file", function() {
                //var exp = /.jpg$|.gif$|.png$|.bmp$/;
                var expFilter = /^(image\/jpeg|image\/gif|image\/png)$/i;
                var file = this.files[0];
                var orientation = 0;

                if (!$(this).val()) {
                    //$("#user_avatar_file_preview").css( "background-image", "url( ./carnival/img/photo_upload.png )" );
                    return false;
                }

                //if( !exp.test(file.value) ){
                if (!expFilter.test(file.type)) {
                    $.fn.poptips("图片不支持，仅支持JPG、GIF、PNG图片格式");
                    return false;
                }
                if((file.size / 1024) > 1024){
                    $.fn.poptips("图片大小不能超过1024KB");
                    return false;
                }

                //$("#user_avatar .user_profile_tip").html( "载入预览中..." );

                EXIF.getData(file, function() {
                    //orientation = EXIF.getTag( this, "Orientation");
                    var file_exif = EXIF.getAllTags(this);
                    orientation = file_exif.Orientation;
                });


                var reader = new FileReader();

                reader.onload = function(e) {

                    $.fn.getimgdata({
                        img: this.result,
                        dir: orientation,
                        max_side: settings.max_side,
                        max_height: settings.max_height,
                        next: function(data) {

                            $("#imgupload_preview").prop("src", data).css({ "width": "", "height": "" });

                            $("#imgupload_file_data").val(data);

                            try {
                                jcrop_api.destroy();
                            } catch (e) {}



                            $("#imgupload_preview").Jcrop({
                                aspectRatio: settings.aspect_ratio,
                                onSelect: updateCoords,
                                onRelease: function() {
                                    $("#btn_crop_ok").off(".click_crop_ok");
                                    $("#btn_crop_cancel").off(".click_crop_cancel");
                                }
                            }, function() {
                                jcrop_api = this;

                                //如果限制了比例则自动裁选
                                if (settings.aspect_ratio) {
                                    var tmp_select_initial = Math.min($("#imgupload_preview").width(), $("#imgupload_preview").height());
                                    jcrop_api.setSelect([0, 0, tmp_select_initial, tmp_select_initial]);
                                }

                            });

                            imgupload_scale = getImgNaturalDimensions(document.getElementById("imgupload_preview"))[0] / $("#imgupload_preview").width();

                        }
                    });


                }

                reader.readAsDataURL(file);

                $("#submit_imgupload").show();

            });


            //取消插入图片
            $("#part_imgupload .btn_cancel, #part_imgupload .mask").on("click.imgupload_cancel", function() {
                settings.btnCancelClick($this_btn);
                $("#part_imgupload").addClass("hide");
                bodyfixed(0);

                $("#crop_bottombar").hide();

                $("#btn_crop_ok").off(".click_crop_ok");
                $("#btn_crop_cancel").off(".click_crop_cancel");
                $("#imgupload_file").off(".change_imgupload_file").val("");
                $("#part_imgupload .btn_cancel, #part_imgupload .btn_cancel").off(".imgupload_cancel");
                $("#submit_imgupload").off(".imgupload_ok");
                $("#imgupload_preview").css({ "width": "", "height": "" });
                try {
                    jcrop_api.destroy();
                } catch (e) {}
            });

            //确认插入图片
            $("#submit_imgupload").on("click.imgupload_ok", function() {

                if (!$("#imgupload_file_data").val()) {
                    $.fn.poptips("请选择需要上传的图片，仅支持JPG、GIF、PNG图片格式");
                    return false;
                }
                if (settings.file_data) {
                    $(settings.file_data).val($("#imgupload_file_data").val());
                }

                settings.btnOKClick($("#imgupload_file_data").val(), $this_btn);

                $("#part_imgupload").addClass("hide");
                bodyfixed(0);

                $("#crop_bottombar").hide();

                $("#btn_crop_ok").off(".click_crop_ok");
                $("#btn_crop_cancel").off(".click_crop_cancel");
                $("#imgupload_file").off(".change_imgupload_file").val("");
                $("#part_imgupload .btn_cancel, #part_imgupload .btn_cancel").off(".imgupload_cancel");
                $("#submit_imgupload").off(".imgupload_ok").attr("style", "");
                $("#imgupload_preview").css({ "width": "", "height": "" });
                try {
                    jcrop_api.destroy();
                } catch (e) {}
            });




        }


        return this;

    }
})(jQuery);
//alert( typeof origi_sports_items );
/** 上传并裁切图片 结束 **/


/**
文本框与范围控件联动
UPDATE: 2018/05/02
Powered by Joyton & dline.com.cn
初始化：
$(".demo").formrange();
重置：
$(".demo").formrange("update", {//参数都是可选的
  "min": 0,
  "max": 100,
  "callback": function(){}
});

**/
(function($) {
    var methods = {
        init: function(callback) { //初始化
            return this.each(function() {
                var $range_linkage = $(this);

                var $input_range = $range_linkage.find("input[type=range]"); //范围控件
                var $input_number = $range_linkage.find("input[type=number]"); //文本框
                var $btn_useall = $range_linkage.find(".btn_useall"); //“使用所有”按钮

                //console.log(settings);
                $input_range.on("input", function() {
                    //console.log( $(this).val() );
                    var $tmp_form_range = $(this).closest(".form_range");
                    var $tmp_bar = $tmp_form_range.find(".form_range_bar");
                    var tmp_percent = (($(this).val() - $(this).attr("min")) / ($(this).attr("max") - $(this).attr("min")) * 100);
                    //console.log( tmp_percent );
                    $tmp_bar.width(tmp_percent + "%");
                    if (tmp_percent >= 50 && tmp_percent < 90) {
                        $tmp_form_range.removeClass("danger").addClass("warning");
                        //$tmp_bar.css("background-color", "green");
                    } else if (tmp_percent >= 90) {
                        $tmp_form_range.removeClass("warning").addClass("danger");
                        //$tmp_bar.css("background-color", "red");
                    } else {
                        $tmp_form_range.removeClass("warning danger")
                            //$tmp_bar.css("background-color", "");
                    }

                    if ($input_number.val() != $(this).val()) {
                        $input_number.val($(this).val());
                    }

                });

                $input_range.on("change", function() {
                    if (typeof callback == "function") {
                        callback({
                            "$dom": $range_linkage,
                            "now": $(this).val(),
                            "max": $input_range.attr("max"),
                            "min": $input_range.attr("min")
                        });
                    }
                });
                $input_number.on("change", function() {
                    $input_range.trigger("change");
                });

                $input_number.on("input", function() {
                    if ($(this).val() == "") {
                        return false;
                    }
                    $input_range.val($(this).val()).trigger("input");
                });

                $btn_useall.on("click", function() {
                    $input_range.val($input_range.attr("max")).trigger("input");
                    $input_range.trigger("change");
                });


            });
        },
        update: function(options) { //重置
            var defaults = {
                "min": "",
                "max": "",
                "callback": function() {},
            };

            if ((typeof options != "object")) {
                defaults.con = options;
            }

            var settings = $.extend({}, defaults, options);

            var $range_linkage = $(this);
            var $input_range = $range_linkage.find("input[type=range]"); //范围控件
            var $input_number = $range_linkage.find("input[type=number]"); //文本框
            if ($.isNumeric(settings.min)) {
                $input_range.attr("min", settings.min);
                $input_number.attr("min", settings.min);
            }
            if ($.isNumeric(settings.max)) {
                $input_range.attr("max", settings.max);
                $input_number.attr("max", settings.max);
            }
            $input_range.trigger("input");
            settings.callback($range_linkage, $input_range.attr("min"), $input_range.attr("max"));
        }
    };
    $.fn.formrange = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === "object" || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error("用法错误，这个 " + method + " 并不存在。");
        }
        return this;
    }
})(jQuery);
/** 文本框与范围控件联动 结束 **/



/* 动态构建表单并提交 */
//$.StandardPost('url/path/req',{arg0:'arg0',arg1:'arg1'});
$.extend({
    StandardPost: function(url, args) {
        var body = $(document.body),
            form = $("<form method='post'></form>"),
            input;
        form.attr({ "action": url });
        $.each(args, function(key, value) {
            input = $("<input type='hidden'>");
            input.attr({ "name": key });
            input.val(value);
            form.append(input);
        });

        form.appendTo(document.body);
        form.submit();
        document.body.removeChild(form[0]);
    }
});


//格式化时间
Date.prototype.format = function(format) {
    var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        } //js格式化
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(format)) {
        format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}



//文本框获得焦点变色
$(document).on("focusin", ".form_input", function() {
    if ($(this).is(".hasborder")) {
        $(this).addClass("focus");
    } else {
        $(this).closest(".form_item").addClass("focus");
    }
});
$(document).on("focusout", ".form_input", function() {
    if ($(this).is(".hasborder")) {
        $(this).removeClass("focus");
    } else {
        $(this).closest(".form_item").removeClass("focus");
    }
});




/************************************************************************************/

$(function() {

    //头部搜索框获得焦点醒目显示
    $("#header").on("focus", ".input_search", function() {
        $("#header").addClass("has_header_search");
        //$( "#header .btn_search" ).show();
    });

    //main_top 自动 fixed
    (function($) {
        $.fn.main_top_needfixed = function() {
            $(".main_top").each(function() {
                if ($(this).hasClass("needfixed")) {
                    if ($(this).closest(".subpage").length) {
                        $(this).closest(".subpage").addClass("main_top_fixed");
                    } else {
                        $("body").addClass("main_top_fixed");
                    }
                    $(this).siblings(".main").css("padding-top", $(this).height());
                }
            });
        }
    })(jQuery);
    $.fn.main_top_needfixed();



    //载入指示器
    $("#loader").addClass("hide");

    $(document).ajaxStart(function() {
        $("#loader").removeClass("hide");
    }).ajaxStop(function() {
        $("#loader").addClass("hide");
    });



    //顶部返回按钮
    if (document.referrer == "") { //history.length <= 1
        $("#header .back").attr("href", site_url);
    }

    //限制数量框只能输入数字
    $("body").on("input", ".input_amount_box .input", function() {
        var tmp_amountnumber = parseInt($(this).val());
        if (isNaN(tmp_amountnumber)) {
            tmp_amountnumber = 1;
        }
        if (tmp_amountnumber > $(this).data("max")) {
            tmp_amountnumber = $(this).data("max");
        }
        if (tmp_amountnumber < 0) {
            tmp_amountnumber = 1;
        }
        $(this).val(tmp_amountnumber);
    });


    //弹出注释
    $("[data-poptips]").each(function() {
        if ($(this).data("poptips")) {
            $(this).on("click", function() {
                $.fn.poptips($(this).data("poptips"));
            });
        }
    });



});



/******** 滚动相关 ********/
$(function() {
    $(window).scroll(function() {


    });
});





/******** 数字跳动 ********/
$.fn.countTo = function(options) {
    options = options || {};

    return $(this).each(function() {
        // set options for current element
        var settings = $.extend({}, $.fn.countTo.defaults, {
            from: $(this).data('from'),
            to: $(this).data('to'),
            speed: $(this).data('speed'),
            refreshInterval: $(this).data('refresh-interval'),
            decimals: $(this).data('decimals')
        }, options);

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(settings.speed / settings.refreshInterval),
            increment = (settings.to - settings.from) / loops;

        // references & variables that will change with each update
        var self = this,
            $self = $(this),
            loopCount = 0,
            value = settings.from,
            data = $self.data('countTo') || {};

        $self.data('countTo', data);

        // if an existing interval can be found, clear it first
        if (data.interval) {
            clearInterval(data.interval);
        }
        data.interval = setInterval(updateTimer, settings.refreshInterval);

        // initialize the element with the starting value
        render(value);

        function updateTimer() {
            value += increment;
            loopCount++;

            render(value);

            if (typeof(settings.onUpdate) == 'function') {
                settings.onUpdate.call(self, value);
            }

            if (loopCount >= loops) {
                // remove the interval
                $self.removeData('countTo');
                clearInterval(data.interval);
                value = settings.to;

                if (typeof(settings.onComplete) == 'function') {
                    settings.onComplete.call(self, value);
                }
            }
        }

        function render(value) {
            var formattedValue = settings.formatter.call(self, value, settings);
            $self.html(formattedValue);
        }
    });
};

$.fn.countTo.defaults = {
    from: 0, // the number the element should start at
    to: 0, // the number the element should end at
    speed: 1000, // how long it should take to count between the target numbers
    refreshInterval: 100, // how often the element should be updated
    decimals: 0, // 小数点 the number of decimal places to show
    formatter: formatter, // handler for formatting the value before rendering
    onUpdate: null, // callback method for every time the element is updated
    onComplete: null // callback method for when the element finishes updating
};

function formatter(value, settings) {
    return value.toFixed(settings.decimals);
}


//插入“查看大图”容器
function fun_insert_photoswipe() {
    var tmp_html = "";
    tmp_html += "<div class=\"pswp\" tabindex=\"-1\" role=\"dialog\" aria-hidden=\"true\">";
    tmp_html += "<div class=\"pswp__bg\"></div>";
    tmp_html += "<div class=\"pswp__scroll-wrap\">";
    tmp_html += "<div class=\"pswp__container\">";
    tmp_html += "<div class=\"pswp__item\"></div><div class=\"pswp__item\"></div><div class=\"pswp__item\"></div>";
    tmp_html += "</div>";
    tmp_html += "<div class=\"pswp__ui pswp__ui--hidden\">";
    tmp_html += "<div class=\"pswp__top-bar\">";
    tmp_html += "<div class=\"pswp__counter\"></div>";
    tmp_html += "<button class=\"pswp__button pswp__button--close\" title=\"关闭 (Esc)\"></button>";
    tmp_html += "<button class=\"pswp__button pswp__button--zoom\" title=\"缩放\"></button>";
    tmp_html += "<div class=\"pswp__preloader\">";
    tmp_html += "<div class=\"pswp__preloader__icn\">";
    tmp_html += "<div class=\"pswp__preloader__cut\">";
    tmp_html += "<div class=\"pswp__preloader__donut\"></div>";
    tmp_html += "</div></div></div></div>";
    tmp_html += "<div class=\"pswp__caption\"><div class=\"pswp__caption__center\"></div></div>";
    tmp_html += "</div></div></div>";
    $(tmp_html).appendTo("body");
}

//表单错误高亮提示
function fun_tipshighlight($tipshighlight_target) {
    if (typeof $tipshighlight_target == "object" && $tipshighlight_target.length) {
        $("#tipshighlight").remove();
        $("<div/>").attr("id", "tipshighlight").appendTo("body");
        $("#tipshighlight").css({
            "width": $tipshighlight_target.outerWidth(),
            "height": $tipshighlight_target.outerHeight(),
            "top": $tipshighlight_target.offset().top,
            "left": $tipshighlight_target.offset().left,
        });
    }
}

//顶栏及返回顶部
$(function() {
    $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
            if ($(window).width() > 1440) {
                $(".header").addClass("header_special");
            }

            $(".totop_btn").addClass("active");
        } else {
            $(".header").removeClass("header_special");
            $(".totop_btn").removeClass("active");
        }
        if ($(window).scrollTop() > 150) {
            $(".header").addClass("header_narrow");
        } else {
            $(".header").removeClass("header_narrow");
        }
    });

    $(".footer_wrap").on("click", ".totop_btn", function() {
        $("body,html").animate({ scrollTop: 0 }, 1000)
    })
});
//展示搜索框
$(document).on("click", ".search_btn", function() {
    $(".header_search").show()
});
$(document).on("click", ".search_close", function() {
    $(".header_search").hide()
})

//导航展开关闭
$(document).on("click", ".header_nav_btnwrap", function() {
        $(this).toggleClass("active");
        //$(".header_nav").toggleClass("active");

        $(".header_nav").slideToggle("fast");
    })
    //字体大小
$(document).on("click", ".font_sizebtn", function() {
    if ($(this).hasClass("big")) {
        $("#news_content,.manage_btnwrap").css("font-size", "20px");
    }
    if ($(this).hasClass("medium")) {
        $("#news_content,.manage_btnwrap").css("font-size", "16px");
    }
    if ($(this).hasClass("small")) {
        $("#news_content,.manage_btnwrap").css("font-size", "12px");
    }
})


//禁止网页选择,复制,右击
document.oncontextmenu = function(evt) {
    evt.preventDefault();
};
document.onselectstart = function(evt) {
    evt.preventDefault();
};

// 载入最新动态
function fun_news() {
    $.ajax({
        type: "POST",
        url: GET_NEWS_LIST,
        dataType: "json",
        data: { pageSize: 8, pageNum: 1, sortType: 1 },
        timeout: 20000,
        success: function(data) {
            var fetch_data = data.data;

            if (data.status == 1) {
                if (!fetch_data.length) {
                    $(".list_latest").html("<div class=\"nothing\">暂无内容</div>");
                    $(".latest_news .manage_btnwrap").hide();
                } else {
                    var $tmp_item = "";
                    $.each(fetch_data, function(i, n) {
                        $tmp_item += '<a class="item" href="./news_info.html?id=' + n.id + '"><div class="text">' + n.title + '</div><div class="time">' + toDateStr(n.createDate) + '</div></a>';

                    });
                    $(".list_latest").append($tmp_item);
                }
            }
        }
    })
};
$(function() {
    $(".header").on("submit", function() {
        //获取url中的参数

        if ($(".header .input_search").val() == "") {
            $.fn.winktips("啥都没写，让我搜啥？？");
            return false;
        };

    });



});